package com.spark.tags;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import com.spark.core.SparkBuilder;
import com.spark.core.SparkContext;
import com.spark.core.XMap;
import com.spark.util.IDGenerator;

public class Tab extends ViewComponent {
	
	private static final String DEFAULT_TEMPLATES = "tab.ftl";
	
	private static final String DEFAULT_CLASSNAME = "s_tab";
	
	protected static final String PROPERTITY_TABS = "tabs";
	protected static final String PROPERTITY_TAB = "tab";
	protected static final String PROPERTITY_TAB_ID = "id";
	protected static final String PROPERTITY_TAB_TITLE = "title";
	protected static final String PROPERTITY_TAB_CLASS = "tabClassName";
	protected static final String PROPERTITY_TAB_STYLE = "tabStyle";
	protected static final String PROPERTITY_TAB_BODY_CLASS = "className";
	protected static final String PROPERTITY_TAB_BODY_STYLE = "style";
	protected static final String PROPERTITY_REF = "ref";
//	protected static final String PROPERTITY_SELECTED = "selected";
	protected static final String PROPERTITY_CLOSEABLE = "closeable";
	protected static final String PROPERTITY_HOST = "host";
	protected static final String PROPERTITY_SHOW_MARGIN_LEFT = "showMarginLeft";
	protected static final String PROPERTITY_MARGIN_LEFT = "marginLeft";
	protected static final String PROPERTITY_BODY_NOBORDER = "bodyNoBorder";
	
	private static final String BODY_WIDTH = "bodyWidth";
	private static final String BODY_HEIGHT = "bodyHeight";
	private static final String BODY_STYLE = "bodyStyle";
	private static final String HEAD_WIDTH = "headWidth";
	private static final String STRIPS = "strips";
	private static final String BODY_STR = "bodys";
	
	
	
	private static final int STRIP_HEIGHT = 27;//24 是strip的高度,2是body的上下边框
	
	public String getTemplate(){
		return DEFAULT_TEMPLATES;
	}
	
	protected String getDefaultClass(XMap view,SparkContext context){
		String className = super.getDefaultClass(view, context);
		StringBuilder sb = new StringBuilder();
		sb.append(className);
		if(!"".equals(className.trim()))sb.append(" ");
		sb.append(DEFAULT_CLASSNAME);
		return sb.toString();
	}
	
	
	
	public void init(XMap view, SparkContext context) throws Exception{
		super.init(view, context);
//		context.addStyleSheet("tab/Tab-min.css");
//		context.addJavaScript("tab/Tab.js");
		StringBuilder sb = new StringBuilder();
		
		context.addJsonConfig(PROPERTITY_HOST, view.getBoolean(PROPERTITY_HOST,false));
		
		boolean noBorder = view.getBoolean(PROPERTITY_BODY_NOBORDER, false);
		Integer bodyWidth = new Integer(((Integer)context.get(PROPERTITY_WIDTH)).intValue() - (noBorder ? 0 : 2));
		Integer bodyHeight = new Integer(((Integer)context.get(PROPERTITY_HEIGHT)).intValue() + (noBorder ? 1 : 0) - STRIP_HEIGHT);
		context.put(BODY_WIDTH, bodyWidth);
//		context.put(HEAD_WIDTH, bodyWidth-34);
		context.put(HEAD_WIDTH, bodyWidth);
		context.put(BODY_HEIGHT, bodyHeight);
		context.put(BODY_STYLE, view.getString(BODY_STYLE,""));		
		context.put(STRIPS, createTabStrips(view,context,sb));
		context.put(BODY_STR, createTabBodys(view,context));
		if((Integer)context.get("stripsWidth") <= bodyWidth){
//		if((Integer)context.get("stripsWidth") <= bodyWidth-36){
			context.put("display", "none");
		}
	}
	
	
	private String createTabBodys(XMap view, SparkContext context) throws IOException{
		StringBuilder sb = new StringBuilder();
		XMap tabs = view.getChild(PROPERTITY_TABS);
		if(tabs!=null) {
			List<XMap> childs = tabs.getChilds();
			if(childs!=null){
				Iterator<XMap> it = childs.iterator();
				
				while(it.hasNext()){
					XMap tab = (XMap)it.next();
					Integer bodywidth = (Integer)context.get(BODY_WIDTH);
					Integer bodyheight = (Integer)context.get(BODY_HEIGHT);
					String ref = tab.getString(PROPERTITY_REF, "");
					String bodyClass = tab.getString(PROPERTITY_TAB_BODY_CLASS, "");
					String bodyStyle = tab.getString(PROPERTITY_TAB_BODY_STYLE, "");
					sb.append("<div class='tab ").append(bodyClass).append("' style='width:").append(bodywidth).append("px;height:").append(bodyheight).append("px;").append(bodyStyle).append("'>");
					if("".equals(ref)){
						List<XMap> tabchilds = tab.getChilds();
						if(tabchilds!=null){
							Iterator<XMap> tit = tabchilds.iterator();
							while(tit.hasNext()){
								XMap tabchild = (XMap)tit.next();
								try {
									sb.append(SparkBuilder.build(tabchild,context));
								} catch (Exception e) {
									throw new IOException(e.getMessage());
								}
							}
						}
					}
					sb.append("</div>");
				}
			}
		}
		return sb.toString();
	}
	
	private String createTabStrips(XMap view,SparkContext context,StringBuilder st){
		List<XMap> jsons = new ArrayList<XMap>(); 
		StringBuilder sb = new StringBuilder();
		XMap tabs = view.getChild(PROPERTITY_TABS);
		
		boolean showMarginLeft = view.getBoolean(PROPERTITY_SHOW_MARGIN_LEFT, false);
		int stripswidth=0;
		if(tabs!=null){
		List<XMap> childs = tabs.getChilds();
			if(childs!=null){
				Iterator<XMap> it = childs.iterator();
				int i = 0;
				while(it.hasNext()){
					XMap tab = (XMap)it.next();
					
					String id = tab.getString(PROPERTITY_TAB_ID);
					if(id == null){
						id = IDGenerator.getInstance().generate();
					}
					String prompt = tab.getString(PROPERTITY_TAB_TITLE, "");
//					prompt = session.getLocalizedPrompt(prompt);
					int width = tab.getInt(PROPERTITY_WIDTH, 70);
					stripswidth += (width+6);
					String target = tab.getString(PROPERTITY_BINDTARGET, "");
					if(!"".equals(target)){
//						if("".equals(id))id = IDGenerator.getInstance().generate();
						String[] ts = target.split(",");
						for(int b=0;b<ts.length;b++){
							String tid = ts[b];
							st.append("$('").append(tid).append("').on('valid',function(ds, record, name, valid){if(!valid && !Ext.get('").append(id).append("').hasActiveFx()) Ext.get('").append(id).append("').frame('ff0000', 3, { duration: 1 })});\n");
						}
						
					}
//					String selected = tab.getString(PROPERTITY_SELECTED, "");
//					if("true".equals(selected)){
//						context.putConfig("selected", new Integer(i));
//						context.addJsonConfig(PROPERTITY_SELECTED, new Integer(i));
//					}
					String tabClass = tab.getString(PROPERTITY_TAB_CLASS, "");
					String tabStyle = tab.getString(PROPERTITY_TAB_STYLE, "");
					String ref = tab.getString(PROPERTITY_REF, "");
					boolean closeable = tab.getBoolean(PROPERTITY_CLOSEABLE, false);
					if("".equals(ref)){
						closeable = false;
					}
					if(!"".equals(tabStyle)){
						tabStyle = "style='"+tabStyle+"'";
					}
					sb.append("<div class='strip unactive' ").append(tabStyle).append(" unselectable='on' ").append(((!"".equals(id)) ? "id='"+id+"'" : "")).append(" onselectstart='return false;'>");
					sb.append("<div class='strip-left ").append(tabClass).append("'></div>");
					sb.append("<div class='strip-center ").append(tabClass).append("' style='width:").append(width).append("px;'>");
					if(closeable){
						sb.append("<div class='tab-close'></div>");
					}
					sb.append(prompt+"</div>");
					sb.append("<div class='strip-right ").append(tabClass).append("'></div>");
					sb.append("</div>");
					
//					tab.putBoolean(PROPERTITY_SELECTED, tab.getBoolean(PROPERTITY_SELECTED, false));
					
					tab.putString(PROPERTITY_REF, ref);
					tab.remove(PROPERTITY_CLOSEABLE);
					tab.remove(PROPERTITY_TAB_TITLE);
					jsons.add(tab);
					i++;
				}
			}
		}
		context.put("stripsWidth", new Integer(stripswidth));
		if(showMarginLeft){
			int left = view.getInt(PROPERTITY_MARGIN_LEFT, 5);
			context.put("showMarginLeft", "margin-left:"+left+"px;");
//			context.addJsonConfig(PROPERTITY_SHOW_MARGIN_LEFT, true);
//			context.addJsonConfig(PROPERTITY_MARGIN_LEFT, left);
			Integer headWidth = (Integer)context.get(HEAD_WIDTH);
			context.put(HEAD_WIDTH, headWidth);
		}
		context.addJsonConfig("items", jsons);
		context.put("items", jsons.toString());
		return sb.toString();
	}
	
	
	@SuppressWarnings("unchecked")
	protected String build(SparkContext context){
		Map map = context.getMap();
		StringBuilder sb = new StringBuilder();
		sb.append("<TABLE cellSpacing=\"0\" id=\"").append(get(map,"id")).append("\" cellPadding=\"0\" border=\"0\" class=\"").append(get(map,"className")).append("\" style=\"width:").append(get(map,"width")).append("px;height:").append(get(map,"height")).append("px;").append(get(map,"style")).append("\">\r");
		sb.append("    <TBODY>\r");
		sb.append("        <TR>\r");
		sb.append("            <TD>\r");
		sb.append("                <DIV stype=\"scroll-left\" class=\"tab-scroll tab-scroll-left scroll-disabled\" style=\"display:").append(get(map,"display")).append("\"></DIV>\r");
		sb.append("                <DIV class=\"s_tab_strip\" style=\"overflow:hidden;width:").append(get(map,"headWidth")).append("px\">\r");
		sb.append("                    <DIV stype=\"tab.strips\" style=\"width:").append(get(map,"stripsWidth")).append("px;height:25px;").append(get(map,"showMarginLeft")).append("\">").append(get(map,"strips")).append("</DIV>\r");
		sb.append("                </DIV>\r");
		sb.append("                <DIV stype=\"scroll-right\" class=\"tab-scroll tab-scroll-right\" style=\"display:").append(get(map,"display")).append("\"></DIV>\r");
		sb.append("            </TD>\r");
		sb.append("        </TR>\r");
		sb.append("        <TR>\r");
		sb.append("            <TD>\r");
		sb.append("                <div class=\"s_tab_body\" style=\"width:").append(get(map,"bodyWidth")).append("px;height:").append(get(map,"bodyHeight")).append("px;").append(get(map,"bodyStyle")).append("\">\r");
		sb.append("                    ").append(get(map,"bodys"));
		sb.append("                </div>\r");
		sb.append("            </TD>\r");
		sb.append("        </TR>\r");
		sb.append("    </TBODY>\r");
		sb.append("</TABLE>\r");
		sb.append("<SCRIPT>new Spark.Tab(").append(get(map,"config")).append(")</SCRIPT>\r");
		return sb.toString();
	}
}
